/***
 * 
 * 封装吸顶组件
 */

import React, { Component, createRef } from 'react';
import styles from './index.module.css'
import propTypes from 'prop-types';

class Sticky extends Component {
  //创建ref对象
  placeholder = createRef()
  content = createRef()
  // 设置吸顶
  handleScroll = () => {
    const { height } = this.props;

    // 获取DOM对象
    const placeholderEl = this.placeholder.current
    const contentEl = this.content.current
    const { top } = placeholderEl.getBoundingClientRect()
    if (top < 0) {
      // 吸顶
      contentEl.classList.add(styles.fixed)
      placeholderEl.style.height = `${height}px`;
    } else {
      // 取消吸顶
      contentEl.classList.remove(styles.fixed)
      placeholderEl.style.height = '0px'
    }
  }
  // 监听 scroll 事件
  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
  }
  render() {
    return (
      <div>
        {/* 占位元素 */}
        <div ref={this.placeholder} />
        <div ref={this.content}>{this.props.children}</div>
        {/* 内容元素 */}

      </div>
    )
  }
}

Sticky.propTypes = {
  height: propTypes.number.isRequired,
}

export default Sticky